# -*- coding: utf-8 -*-
# 高级特性----map/reduce

# map()函数接收两个参数，一个是函数，一个是Iterable，map将传入的函数依次作用到序列的每个元素，并把结果作为新的Iterator返回


# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上，这个函数必须接收两个参数，reduce把结果继续和序列的下一个元素做累积计算，其效果就
# reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

import io
import sys
from functools import reduce

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

def f(x):
	return x*x

r = map(f,[1,2,3,4,5,6,7,8,9,10])
print(list(r)) 

print(list(map(str,[1,2,3,4,5,6,7,8,9,10])))

def add(x,y):
	return x+y
r = reduce(add,[1,2,3,4,5,6,7,8,9,10])
print(r)


def fn(x,y):
	return x * 10 +y

def char2num(x):
	digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
	return digits[x]

print(reduce(fn,[1,2,3,4,5,6]))
print(reduce(fn,map(char2num,'123456')))

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def char2num(s):
    return DIGITS[s]

def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))
print(str2int('123456'))

def normalize(s):
	return s[0].upper() + s[1:].lower()

# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

def prod(s):
	return reduce(lambda x,y: x * y,s)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')

def str2float(s):
	i = s.find('.')
	a,b = list(map(int,s[:i])),list(map(int,s[i+1:]))
	return reduce(lambda x,y:x*10+y,a) + reduce(lambda x,y:x*0.1+y,b[::-1])*0.1

print('str2float(\'123.456\') =', str2float('123.456'))
print(str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')

print('123.456'[::-1])